import Vue from 'vue'
import Vuex from 'vuex'
import { getLocal, setLocal, login, clearLocal } from '@/common/utils'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: "",
    count: 0,
    loginModel: localStorage.getItem('loginModel') ||'staff',
    jobNum: localStorage.getItem('jobNum') || 0
  },
  getters: {
    getToken(state) {
      return state.token||getLocal("token");
    },
    getLoginModel: (state) => state.loginModel,
    getJobNum: (state) => state.jobNum,

  },
  mutations: {
    changeToken(state, token) {
        state.token = token;
        setLocal("token",token);
    },
    logout(state) {
      state.token = "";
      clearLocal("token")  // 清除 localStorage 中的 token
    },
    increment(state) {
      state.count++;
    },
    setJobNum(state, jobNum) {
      state.jobNum = jobNum;
      localStorage.setItem('jobNum', jobNum);  // 保存到 localStorage
    },
    setLoginModel(state, model) {
      state.loginModel = model;
      localStorage.setItem('loginModel', model);  // 保存到 localStorage
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
          commit('increment');
      }, 2000);
    },
    async login({ commit }, { account, password }) {
      try {
        const response = await login({ account, password });
        commit('changeToken', response.token);
        console.log('Login successful:', response.token);
        return true;
      } catch (error) {
        return false;
      }
    },
    updateLoginModel({ commit }, model) {
      commit('setLoginModel', model);
    },
    updateJobNum({ commit }, jobNum) {
      commit('setJobNum', jobNum);
    }
  },
  modules: {
  }
})

